<template>
  <view class="letter_container">
    <view class="letter_content">
      <view class="content">
        <view class="content_letter">
          {{ currentWord.upper }}
        </view>
        <view class="content_letter active">
          {{ currentWord.lower }}
        </view>
      </view>
      <view class="noop" v-if="!isRecord"></view>
      <view class="record" v-else-if="!isSuspend">
        <view class="record_time">
          正在录音{{ minuteNumber }}:{{ secondNumber }}
        </view>
        <RecordShape></RecordShape>
      </view>
      <view class="load" v-else-if="isSuspend && !isHandle">
        <u-loading mode="flower" size="96"></u-loading>
      </view>
      <view class="result" v-else-if="isSuspend && isHandle">
        <view class="result_content">
          <text class="result_content_text">
            {{ score }}
          </text>
          <text class="result_content_text">
            分
          </text>
          <view class="result_info active" v-if="isPass">
            <text>过关</text>
          </view>
          <view class="result_info" v-else>
            <text>未过关</text>
          </view>
        </view>
        <view class="phoneme">
          <view class="phoneme_title">
            <text>标准发音</text>
            <text>音素匹配</text>
          </view>
          <view class="phoneme_container">
            <view
              class="phoneme_content"
              v-for="(item, index) in syllArray"
              :key="index"
            >
              <text>{{ item.content }}</text>
              <text
                class="error"
                :class="{
                  correct: item.score >= 60,
                }"
                >{{ item.score }}</text
              >
            </view>
          </view>
        </view>
      </view>
      <view class="icon">
        <view class="icon_content">
          <view class="icon_iamge" @click="play()">
            <image
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/sound.png"
              mode="widthFix"
              style="width:74rpx"
            ></image>
          </view>
          <view class="icon_text">
            听声音
          </view>
        </view>
        <view class="icon_content" v-if="!isRecord" @click="record()">
          <view class="icon_iamge">
            <image
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/voice.png"
              mode="widthFix"
              style="width:52rpx"
            ></image>
          </view>
          <view class="icon_text">
            开始录音
          </view>
        </view>
        <view class="icon_content" v-else-if="!isSuspend" @click="endRecord()">
          <view class="icon_iamge">
            <image
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/suspend.png"
              mode="widthFix"
              style="width:56rpx"
            ></image>
          </view>
          <view class="icon_text">
            结束录音
          </view>
        </view>
        <view class="icon_content" v-else-if="isSuspend && !isHandle">
          <view class="icon_iamge">
            <image
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/wait.png"
              mode="widthFix"
              style="width:63rpx"
            ></image>
          </view>
          <view class="icon_text">
            处理中
          </view>
        </view>
        <view
          class="icon_content"
          v-else-if="isSuspend && isHandle"
          @click="playVoice()"
        >
          <view class="icon_iamge">
            <image
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/play.png"
              mode="widthFix"
              style="width:43rpx"
            ></image>
          </view>
          <view class="icon_text">
            我的录音
          </view>
        </view>
      </view>
    </view>
    <view class="button">
      <view class="button_container">
        <view class="button_content" @click="practiceAgain()" v-if="showAnswer">
          <image
            src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/ace_button1.png"
            mode="widthFix"
            style="width:180rpx"
          ></image>
        </view>
      </view>
      <view class="button_container">
        <view
          class="button_content active"
          @click="nextQuestion()"
          v-if="isPass && showAnswer"
        >
          <image
            src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/ace_button2.png"
            mode="widthFix"
            style="width:140rpx"
          ></image>
        </view>
      </view>
    </view>
    <Tips :show="showTips" :content="tipsContent"></Tips>
  </view>
</template>

<script>
import permision from "@/js_sdk/wa-permission/permission.js";
import parser from "fast-xml-parser";
import dictList from "@/libs/PronunciationDict";

const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
const englishAudioContext = uni.createInnerAudioContext();
englishAudioContext.autoplay = true;

export default {
  components: {},
  data() {
    return {
      isIos: true,
      voicePath: "",
      recordOptions: {
        duration: 60000,
        sampleRate: 16000,
        encodeBitRate: 48000,
      },
      permisionIosMap: {
        location: "位置",
        camera: "摄像头",
        photoLibrary: "相册",
        record: "麦克风",
        push: "推送",
        contact: "通讯录",
        calendar: "日历",
        memo: "备忘录",
      },
      permisionAndroidMap: {
        "android.permission.ACCESS_FINE_LOCATION": "位置",
        "android.permission.ACCESS_COARSE_LOCATION": "模糊位置",
        "android.permission.CAMERA": "摄像头",
        "android.permission.READ_EXTERNAL_STORAGE": "外部存储(含相册)读取",
        "android.permission.WRITE_EXTERNAL_STORAGE": "外部存储(含相册)写入",
        "android.permission.RECORD_AUDIO": "麦克风",
        "android.permission.READ_CONTACTS": "通讯录读取",
        "android.permission.WRITE_CONTACTS": "通讯录写入",
        "android.permission.READ_CALENDAR": "日历读取",
        "android.permission.WRITE_CALENDAR": "日历写入",
        "android.permission.READ_SMS": "短信读取",
        "android.permission.SEND_SMS": "短信发送",
        "android.permission.RECEIVE_SMS": "接收新短信",
        "android.permission.READ_PHONE_STATE": "获取手机识别码等信息的",
        "android.permission.CALL_PHONE": "拨打电话",
        "android.permission.READ_CALL_LOG": "获取通话记录",
      },
      wordList: [
        {
          upper: "A",
          lower: "a",
        },
        {
          upper: "B",
          lower: "b",
        },
        {
          upper: "C",
          lower: "c",
        },
        {
          upper: "D",
          lower: "d",
        },
        {
          upper: "E",
          lower: "e",
        },
        {
          upper: "F",
          lower: "f",
        },
        {
          upper: "G",
          lower: "g",
        },
        {
          upper: "H",
          lower: "h",
        },
        {
          upper: "I",
          lower: "i",
        },
        {
          upper: "J",
          lower: "j",
        },
        {
          upper: "K",
          lower: "k",
        },
        {
          upper: "L",
          lower: "l",
        },
        {
          upper: "M",
          lower: "m",
        },
        {
          upper: "N",
          lower: "n",
        },
        {
          upper: "O",
          lower: "o",
        },
        {
          upper: "P",
          lower: "p",
        },
        {
          upper: "Q",
          lower: "q",
        },
        {
          upper: "R",
          lower: "r",
        },
        {
          upper: "S",
          lower: "s",
        },
        {
          upper: "T",
          lower: "t",
        },
        {
          upper: "U",
          lower: "u",
        },
        {
          upper: "V",
          lower: "v",
        },
        {
          upper: "W",
          lower: "w",
        },
        {
          upper: "X",
          lower: "x",
        },
        {
          upper: "Y",
          lower: "y",
        },
        {
          upper: "Z",
          lower: "z",
        },
      ],
      currentIndex: 0,
      syllArray: [],
      timerId: null,
      second: 0,
      minute: 0,
      secondNumber: "00",
      minuteNumber: "00",
      isRecord: false,
      isSuspend: false,
      isHandle: false,
      isRejected: "false",
      score: 0,
      isPass: false,
      showAnswer: false,
      isShowPopup: false,
      isCanClick: true,
      showTips: false,
      tipsContent: "请不要乱读哦~",
    };
  },
  computed: {
    currentWord() {
      return this.wordList[this.currentIndex] || {};
    },
  },
  created() {
    // #ifdef APP-PLUS
    this.isIos = plus.os.name == "iOS";
    // #endif
    let self = this;
    recorderManager.onStop(function(res) {
      self.voicePath = res.tempFilePath;
      self.uploadVoice();
    });
  },
  methods: {
    initData() {
      this.isRecord = false;
      this.isSuspend = false;
      this.isHandle = false;
      this.showAnswer = false;
    },
    record() {
      if (!this.isCanClick) return;
      this.isCanClick = false;
      setTimeout(() => {
        this.isCanClick = true;
      }, 1000);
      if (this.isIos) {
        this.judgeIosPermission("record");
      } else {
        this.requestAndroidPermission("android.permission.RECORD_AUDIO");
      }
    },
    judgeIosPermission: function(permisionID) {
      var result = permision.judgeIosPermission(permisionID);
      var strStatus = result ? "已" : "未";
      if (!result) {
        uni.showModal({
          title: "",
          content:
            this.permisionIosMap[permisionID] +
            "权限" +
            strStatus +
            "获得授权,是否去开启？",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              plus.runtime.openURL("app-settings://");
            }
          },
        });
      } else {
        this.startRecord();
      }
    },
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);
      var strStatus;
      if (result == 1) {
        strStatus = "已获得授权";
        this.startRecord();
      } else if (result == 0) {
        strStatus = "未获得授权";
      } else {
        strStatus = "被永久拒绝权限";
        uni.showModal({
          title: "",
          content: this.permisionAndroidMap[permisionID] + "权限" + strStatus,
          showCancel: false,
        });
      }
    },
    startRecord() {
      recorderManager.start(this.recordOptions);
      this.time();
      this.isRecord = true;
    },
    endRecord() {
      this.isSuspend = true;
      recorderManager.stop();
      clearInterval(this.timerId);
      this.second = 0;
      this.minute = 0;
    },
    playVoice() {
      if (!englishAudioContext.paused) return;
      if (this.voicePath) {
        innerAudioContext.src = this.voicePath;
        innerAudioContext.play();
      }
    },
    uploadVoice() {
      this.$upload(this.voicePath, { wordText: this.currentWord.lower }).then(
        (res) => {
          let xml = res.data;
          let grade = parser.parse(xml, {
            attributeNamePrefix: "",
            ignoreAttributes: false,
          });
          if (grade) {
            let read_chapter =
              grade.xml_result.read_sentence.rec_paper.read_chapter;
            this.getSyllData(read_chapter);
            this.isRejected = read_chapter.is_rejected;
            if (this.isRejected === "true") {
              this.showTips = true;
              setTimeout(() => {
                this.showTips = false;
              }, 2000);
            }
            this.score = Number(read_chapter.total_score).toFixed(2);
            this.isPass = this.score >= 60 ? true : false;
            this.isHandle = true;
            this.showAnswer = true;
          }
        }
      );
    },
    time() {
      this.timerId = setInterval(() => {
        this.second++;
        if (this.second > 59) {
          this.second = 0;
          this.minute++;
        }
        if (this.second < 10) {
          this.secondNumber = this.second.toString().padStart(2, "0");
        } else {
          this.secondNumber = this.second.toString();
        }
        if (this.minute < 10) {
          this.minuteNumber = this.minute.toString().padStart(2, "0");
        } else {
          this.minuteNumber = this.minute.toString();
        }
      }, 1000);
    },
    play() {
      if (!englishAudioContext.paused) return;
      englishAudioContext.src =
        "https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/audio/app/" +
        this.currentWord.lower +
        ".mp3";
      englishAudioContext.play();
    },
    getSyllData(result) {
      let syllArray = [];
      let sentence = result.sentence;
      let anArray = [];
      if (!Array.isArray(sentence)) {
        anArray.push(sentence);
      } else {
        anArray = sentence;
      }
      anArray.forEach((item) => {
        let anWordArray = [];
        if (!Array.isArray(item.word)) {
          anWordArray.push(item.word);
        } else {
          anWordArray = item.word;
        }
        anWordArray.forEach((item) => {
          if (item.content === "fil" || item.content === "sil") return;
          let anSyllArray = [];
          if (!Array.isArray(item.syll)) {
            anSyllArray.push(item.syll);
          } else {
            anSyllArray = item.syll;
          }
          anSyllArray.forEach((item) => {
            let syll_score = Number(item.syll_score).toFixed(2);
            const nonStandard = item.content;
            const splitResult = nonStandard.split(" "); // 分割成 ["eh", "m"]
            const standardResult = splitResult
              .map((phoneme) => {
                const found = dictList.find(
                  (item) => item.nonstandard === phoneme
                );

                return found ? found.standard : phoneme; // 如果找到映射则替换，否则保持原样
              })
              .join(" ");
            let syll_content = standardResult;
            syllArray.push({
              content: syll_content,
              score: syll_score,
            });
          });
        });
      });
      this.syllArray = syllArray;
    },
    practiceAgain() {
      this.initData();
    },
    nextQuestion() {
      if (this.currentIndex === this.wordList.length - 1) {
        this.currentIndex = 0;
      } else {
        this.currentIndex++;
      }
      this.initData();
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./LetterITrain";
</style>
